﻿using Tszy.Unlimited.Base.Features;
using Tszy.Unlimited.Data.FreeSQL;

namespace Tszy.Unlimited.Data.Features;

/// <summary>
/// 使用 FreeSQL 做为事务。
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
public abstract class FreeSQLTransactionFunctionFeatureHandler<TRequest, TResponse> : FunctionFeatureHandler<TRequest, TResponse>
    where TRequest : FunctionFeatureRequest<TResponse>
{
    protected readonly IFreeSQLUnitOfWorkFactory _unitOfWorkFactory;

    protected FreeSQLTransactionFunctionFeatureHandler(IFreeSQLUnitOfWorkFactory unitOfWorkFactory, bool transaction = true) : base(transaction)
    {
        _unitOfWorkFactory = unitOfWorkFactory;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    protected override async Task OnHandleAsync(TRequest request, CancellationToken cancellationToken)
    {
        if (transaction)
        {
            using var context = _unitOfWorkFactory.Begin();

            await OnExecuteAsync(request, cancellationToken);

            context.Commit();
        }
        else
        {
            await OnExecuteAsync(request, cancellationToken);
        }
    }
}

/// <summary>
/// 使用 FreeSQL 做为事务。
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
public abstract class FreeSQLTransactionFunctionRecordFeatureHandler<TRequest, TResponse> : FunctionRecordFeatureHandler<TRequest, TResponse>
    where TRequest : FunctionRecordFeatureRequest<TResponse>
{
    protected readonly IFreeSQLUnitOfWorkFactory _unitOfWorkFactory;

    protected FreeSQLTransactionFunctionRecordFeatureHandler(IFreeSQLUnitOfWorkFactory unitOfWorkFactory, bool transaction = true) : base(transaction)
    {
        _unitOfWorkFactory = unitOfWorkFactory;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    protected override async Task OnHandleAsync(TRequest request, CancellationToken cancellationToken)
    {
        if (transaction)
        {
            using var context = _unitOfWorkFactory.Begin();

            await OnExecuteAsync(request, cancellationToken);

            context.Commit();
        }
        else
        {
            await OnExecuteAsync(request, cancellationToken);
        }
    }
}